package com.zxy.leetcode._00000_00099._00000_00009;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 */
public class Test00002 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;

        ListNode node10 = new ListNode(5);
        ListNode node11 = new ListNode(6);
        ListNode node12 = new ListNode(4);
        node10.next = node11;
        node11.next = node12;

        ListNode ret = new Test00002().addTwoNumbers(node1, node10);
        while (ret != null) {
            System.out.println(ret.val);
            ret = ret.next;
        }

    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        ListNode tail = head;
        int c = 0;

        while(true) {
            if (l1 == null && l2 == null) {
                break;
            }

            int a = 0;
            int b = 0;
            if (l1 != null) {
                a = l1.val;
            }
            if (l2 != null) {
                b = l2.val;
            }

            ListNode node = new ListNode();
            int sum = a + b + c;
            node.val = sum % 10;
            c = sum / 10;
            tail.next = node;
            tail = node;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }

        // 最后的进位
        if (c > 0) {
            ListNode node = new ListNode();
            node.val = c;
            tail.next = node;
        }

        return head.next;
    }

}


class ListNode {
    int val;
    ListNode next;

    ListNode() {}

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

}
